﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using devtm.Aop.InternalProcess.Cache;

namespace devtm.Aop.InternalProcess.Lock
{
    
    public class LockDictionnary
    {

        protected Hashtable _lock = new Hashtable();
        protected Hashtable _strategy = new Hashtable();

        public bool Get<T>(uint key, out T cacheItem)
            where T : LockItem
        {

            bool ret = false;

            if (!_lock.ContainsKey(key))
            {

                lock (_lock.SyncRoot)

                    if (!_lock.ContainsKey(key))
                    {
                        _lock.Add(key, (cacheItem = (T)Activator.CreateInstance(typeof(T), new object[] { key })));
                        ret = true;
                    }
                    else
                        cacheItem = _lock[key] as T;

            }
            else
                cacheItem = _lock[key] as T;
            
            return ret;

        }



        internal T GetInstanceStrategyFor<T>(Type strategyType)
            where T : class, ILockStrategy
        {

            if (strategyType == typeof(CacheStrategy))
                return CacheStrategy as T;

            else if (strategyType == typeof(LockStrategy))
                return LockStrategy as T;


            T c = default(T);

            if (!_strategy.ContainsKey(strategyType))
            {

                lock (_strategy.SyncRoot)

                    if (!_strategy.ContainsKey(strategyType))
                        _strategy.Add(strategyType, (c = (T)Activator.CreateInstance(strategyType)));
                    else
                        c = (T)_strategy[strategyType];

            }
            else
                c = (T)_strategy[strategyType];

            return c;

        }


        private CacheStrategy CacheStrategy = new CacheStrategy();

        private LockStrategy LockStrategy = new LockStrategy();

    }
}
